#include <jni.h>
#include <stdio.h>
#include "IntArray.h"
/*
Get<Type>ArrayRegion
Set<Type>ArrayRegion
Copies the contents of primitive arrays to or from a preallocated C buffer.

Get<Type>ArrayElements
Release<Type>ArrayElements
Obtains a pointer to the contents of a primitive array.May return a copy of the array.

GetArrayLength 
Returns the number of elements in the array.

New<Type>Array 
Creates an array with the given length.

GetPrimitiveArrayCritical
ReleasePrimitiveArrayCritical
Obtains or releases a pointer to the contents of a primitive array. May disable garbage collection, or return a copy of the array.

Choosing among the Primitive Array Functions:
Preallocated
C array buffer,
small fixed-size ------------------Y----------------------->Get<type>ArrayRegion
arrays, or small					Set<type>ArrayRegion
subarrays
	|
	N
	|
	v
Targeting            1.2 and beyond	Any blocking or
release 1.1 or ---------------------------------->JNI calls while
1.2?					accessing array
	|				contents?
1.1 or both	-----------------------Y--------------------|
	|	|				N
	|	|				|
	v	v				v
Get<type>ArrayElements 		GetPrimitiveArrayCritical
Release<Type>ArrayElements		ReleasePrimitiveArrayCritical

*/
JNIEXPORT jint JNICALL Java_IntArray_sumArray (JNIEnv * env, jobject obj, jintArray arr) 
{
#if 0
	jint buf[10];
	jint i, sum = 0;
	(*env)->GetIntArrayRegion(env, arr, 0, 10, buf);
	for (i = 0; i < 10; ++i) {
		sum += buf[i];
	}
	return sum;
#else
	jint *carr;
	jint i, sum = 0;
	carr = (*env)->GetIntArrayElements(env, arr, NULL);
	if (carr == NULL) {
		return 0; /* exception occurred */
	}
	for (i=0; i<10; i++) {
		sum += carr[i];
	}
	(*env)->ReleaseIntArrayElements(env, arr, carr, 0);
	return sum;	
#endif	
}